/**
 * 
 */
package com.feonix.nio.test.scatterandgatter;

import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @CopyRight (c)1993-2017
 * @Project common_practice
 * @Comments 请输入该类的描述
 * @NameSpace com.feonix.nio.test.scatterandgatter
 * @Author Feonixzw
 * @CreateDate 2018年3月12日
 */
public class PipeDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		method1();
	}

	public static void method1() {
		Pipe pipe = null;
		ExecutorService exec = Executors.newFixedThreadPool(2);
		try {
			pipe = Pipe.open();
			final Pipe tmpPipe = pipe;
			exec.submit(new Callable<Object>() {

				@Override
				public Object call() throws Exception {
					SinkChannel sinkChannel = tmpPipe.sink();
					while (true) {
						TimeUnit.SECONDS.sleep(1);
						String str = "Pipe test at time: " + System.currentTimeMillis();
						ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
						byteBuffer.clear();
						byteBuffer.put(str.getBytes());
						byteBuffer.flip();
						while (byteBuffer.hasRemaining()) {
							sinkChannel.write(byteBuffer);
						}
					}
				}
			});

			exec.submit(new Callable<Object>() {

				@Override
				public Object call() throws Exception {
					SourceChannel sourceChannel = tmpPipe.source();
					while (true) {
						TimeUnit.SECONDS.sleep(1);
						ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
						byteBuffer.clear();
						int bytesRead = sourceChannel.read(byteBuffer);
						System.out.println("bytesRead=" + bytesRead);
						while (bytesRead > 0) {
							byteBuffer.flip();
							byte[] bytes = new byte[bytesRead];
							int i = 0;
							while (byteBuffer.hasRemaining()) {
								bytes[i] = byteBuffer.get();
								System.out.printf("%X", bytes[i++]);
							}
							String str = new String(bytes);
							System.out.println("=================||" + str);
							bytesRead = sourceChannel.read(byteBuffer);
						}
					}
				}
			});
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			exec.shutdown();
		}
	}

}
